package com.quectel.cms.controller.workorder;


import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.workorder.dto.WorkOrderServiceItemDto;
import com.quectel.core.module.workorder.service.WorkOrderServiceItemService;
import com.quectel.util.common.*;
import com.quectel.util.kit.PageFetchKit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/10/12 17:37
 */
@RestController
@RequestMapping("workOrderServiceItem")
@Tag(name = "WorkOrderServiceItemController", description = "工单服务项目相关api")
public class WorkOrderServiceItemController extends BaseController {

    @DubboReference
    private WorkOrderServiceItemService workOrderServiceItemService;


    /**
     * 导出开票申请记录
     */
    @GetMapping("exportExcel")
    @RequirePermissions(values = "workOrderServiceItem:exportExcel")
    @Operation(description = "导出工单收费标准")
    public void exportExcel(HttpServletRequest httpServletRequest, HttpServletResponse hresp) {
        Request request = Request.configParamsNotPage(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());

        if (request.isNotBlank(SystemConstants.STATUS_FLAG)) {
            String[] statusArrays = request.getString(SystemConstants.STATUS_FLAG).split(",");
            request.put(SystemConstants.STATUSES, statusArrays);
        }

        List<WorkOrderServiceItemDto> result = PageFetchKit.fetchAll(reqParams -> workOrderServiceItemService.queryList(reqParams), request.getParams(), 500);

        String[] headers = new String[]{"所属小区", "服务内容", "收费标准（元）", "单位", "状态", "创建人", "创建时间", "修改人", "修改时间"};
        List<String[]> dataList = new ArrayList<>();
        for (WorkOrderServiceItemDto data : result) {
            String[] item = new String[headers.length];
            item[0] = data.getVillageName();
            item[1] = data.getName();
            item[2] = String.valueOf(data.getShouldPay());
            item[3] = data.getUnit();
            item[4] = SysCodeUtils.easyToGetName(SysCodeKeyConstants.COMMON_STATUS, String.valueOf(data.getStatus()));
            item[5] = data.getCreator();
            item[6] = data.getCreateTime() != null ? DateUtils.format(data.getCreateTime(), DateUtils.FormatType.SIMPLE) : null;
            item[7] = data.getEditor();
            item[8] = data.getEditTime() != null ? DateUtils.format(data.getEditTime(), DateUtils.FormatType.COMMON) : null;
            dataList.add(item);
        }
        POIUtils.exportExcel(hresp, "工单收费标准", headers, dataList, "工单收费标准");

    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "workOrderServiceItem:list")
    @Operation(summary = "分页列表")
    public Response<Page<WorkOrderServiceItemDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = workOrderServiceItemService.queryTotal(request.getParams());

        List<WorkOrderServiceItemDto> list = null;
        if (total > 0) {
            list = workOrderServiceItemService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<WorkOrderServiceItemDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<WorkOrderServiceItemDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "workOrderServiceItem:edit")
    @Operation(summary = "查询单条记录")
    public Response<WorkOrderServiceItemDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (workOrderServiceItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        WorkOrderServiceItemDto workOrderServiceItemDto = workOrderServiceItemService.selectById(id);

        return Response.<WorkOrderServiceItemDto>ok().wrap(workOrderServiceItemDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "workOrderServiceItem:info")
    @Operation(summary = "查询单条记录")
    public Response<WorkOrderServiceItemDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (workOrderServiceItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        WorkOrderServiceItemDto workOrderServiceItemDto = workOrderServiceItemService.selectById(id);

        return Response.<WorkOrderServiceItemDto>ok().wrap(workOrderServiceItemDto);
    }

    /**
     * 保存
     *
     * @param workOrderServiceItemDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "workOrderServiceItem:edit")
    @Operation(summary = "保存单条记录")
    public Response<Object> save(@RequestBody @Validated WorkOrderServiceItemDto workOrderServiceItemDto) {

        //填充基础数据
        fillSaveCommonData(workOrderServiceItemDto);

        workOrderServiceItemService.save(workOrderServiceItemDto);

        return Response.ok();
    }


    /**
     * 修改
     *
     * @param workOrderServiceItemDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "workOrderServiceItem:edit")
    @Operation(summary = "修改单条记录")
    public Response<Object> update(@RequestBody @Validated WorkOrderServiceItemDto workOrderServiceItemDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(workOrderServiceItemDto.getId()));
        if (workOrderServiceItemService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        //填充基础数据
        fillEditCommonData(workOrderServiceItemDto);

        workOrderServiceItemService.updateById(workOrderServiceItemDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "workOrderServiceItem:delete")
    @Operation(summary = "批量删除记录")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (workOrderServiceItemService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        workOrderServiceItemService.deleteBatch(ids);

        return Response.ok();
    }
}
